package com.juicygames.framework.draw.drawservice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.juicygames.framework.action.EntityDestroyedAction;
import com.juicygames.framework.draw.DrawDepth;
import com.juicygames.framework.gamepart.GameEntity;
import com.juicygames.framework.gamepart.GameHandler;
import com.juicygames.framework.gamepart.GamePart;

public class DrawService extends GamePart {
	
	private List<Drawable> drawables;

	public void load() {
		addPart(new DrawHandler());
		drawables = new CopyOnWriteArrayList<Drawable>();
		addPart(new EntityDestroyedHandler(this));
	}

	public <G extends GameHandler> void register(G handler) {
		Drawable drawable = new Drawable();
		drawable.entity = handler.getSelf();
		drawable.depth = handler.getSelf().getPart(DrawDepth.class);
		drawable.drawHandler = handler;
		
		drawables.add(drawable);
		
		// don't yell when you read this
		ArrayList<Drawable> sortableList = new ArrayList<Drawable>(drawables);
		Collections.sort(sortableList);
		drawables = new CopyOnWriteArrayList<Drawable>(sortableList);
	}
	
	public List<Drawable> getDrawables() {
		return drawables;
	}
	
	public void removeEntity(GameEntity entity) {
		for (Drawable drawable : drawables) {
			if (drawable.entity == entity) {
				drawables.remove(drawable);
			}
		}
	}
	

	public class EntityDestroyedHandler extends GameHandler<EntityDestroyedAction> {
		
		private DrawService drawService;
		
		public EntityDestroyedHandler(DrawService drawService) {
			this.drawService = drawService;
		}
		
		public void load() {
			groundHandler();
		}
		
		public Class<EntityDestroyedAction> getActionClassHandled() {
			return EntityDestroyedAction.class;
		}
		
		public void handle(EntityDestroyedAction entityDestroyed) {
			drawService.removeEntity(entityDestroyed.getEntity());
		}
	}

}
